<?php
require('lib/verify.php');
require('lib/has_char.php');
require('lib/is_approved.php');

// ?id=(item)&level=(level) //0 to clear

$wish_item = $_GET["id"];
$wish_level = $_GET["level"];
$wish_src = $_GET["src"];
$character_id = $character["character_id"];
$system_id = $system["system_id"];


//step 0: are wishes locked?
$locked = $system["system_locked"];


if($locked == 1) {
    if(eregi("\?", $wish_src)) {
        header("Location: $wish_src&error=Wishlists+are+currently+locked.");
        exit;
    } else {
        header("Location: $wish_src?error=Wishlists+are+currently+locked.");
        exit;
    }
 }


//step 1: check if the wish already exists

$sql = "select * from wm_wishes where wish_item = $wish_item and wish_character = $character_id and wish_system_id=$system_id";
$result = $db->query($sql);
$wish = $db->fetch_assoc($result);
$old_wish = $wish['wish_level'];

$log_entry = "";

if($db->num_rows($result)>0) {
    //step 2: if it does, update it
    //unless it's a non, in which case delete it

    if($wish_level > 0) {
        //update it
        $sql = "update wm_wishes set wish_level = $wish_level where wish_item = $wish_item and wish_character = $character_id and wish_system_id=$system_id";

        $log_entry = "Wish on $wish_item set to $wish_level (was $old_wish).";
        $result = $db->query($sql);
    } else {
        //delete it
        $sql = "delete from wm_wishes where wish_item = $wish_item and wish_character = $character_id and wish_system_id=$system_id";
        $log_entry = "Wish on $wish_item removed (was $old_wish).";
        $result = $db->query($sql);
    }
} else {
   if ($wish_level > 0) {
       //step 2b: if it doesn't, insert it
       $sql = "insert into wm_wishes (wish_item, wish_character, wish_level, wish_system_id) values ('$wish_item', '$character_id', '$wish_level', '$system_id')";
       $result = $db->query($sql);
       $log_entry = "Wish on $wish_item created, level $wish_level.";
   } else {
       // Wierd situation; We found no bid on this item for this character in this system and yet we try to insert a '0' bid.
       $log_entry = "ERRER: '0' wish detected. src: '$src'";
   }
}

$now = time();

$sql = "insert into wm_logs (log_character, log_type, log_description, log_datetime, log_system_id) values ($character_id, 'Wish', '$log_entry', FROM_UNIXTIME($now), $system_id)";
$result = $db->query($sql);

header("Location: $wish_src");

?>

